import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input } from 'antd';
import React from 'react';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

import { useSelector } from '../../redux/hooks';
import { signIn } from '../../redux/user/slice';
import styles from './sign-in-form.module.css';

type FieldType = {
  email?: string;
  password?: string;
  remember?: boolean;
};

export const SignInForm: React.FC = () => {
  const loading = useSelector((s) => s.user.loading);
  const jwt = useSelector((s) => s.user.token);
  const dispatch = useDispatch();
  const history = useHistory();

  // 监听jwt的变化
  useEffect(() => {
    if (jwt !== null) {
      history.push('/');
    }
  }, [jwt]);
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    dispatch(signIn({ email: values.email, password: values.password }) as any);
  };
  return (
    <Form
      className={styles['register-form']}
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      autoComplete="off"
    >
      <Form.Item<FieldType>
        label="email"
        name="email"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item<FieldType>
        label="Password"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item<FieldType>
        name="remember"
        valuePropName="checked"
        wrapperCol={{ offset: 8, span: 16 }}
      >
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit" loading={loading}>
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};
